import React from 'react';
import { Navigate } from 'react-router-dom';
import {
    DashboardOutlined,
    EnvironmentOutlined,
    SettingOutlined,
    DatabaseOutlined,
    BulbOutlined,
    SwapOutlined,
} from '@ant-design/icons';

// 懒加载页面组件
import Dashboard from '../pages/Dashboard';
import SampleManagement from '../pages/SampleManagement';
import DeviceManagement from '../pages/DeviceManagement';
import DataQuery from '../pages/DataQuery';
import DataComparison from '../pages/DataComparison';
import TabDemo from '../pages/TabDemo';
import ThemeAnimationDemo from '../pages/ThemeAnimationDemo';
import Login from '../pages/Login';
import Forbidden from '../pages/Forbidden';

/**
 * 路由配置
 * 一份配置同时用于路由生成和菜单生成，避免重复维护
 */
export const routeConfig = [
    {
        path: '/',
        element: <Navigate to="/dashboard" replace />,
        showInMenu: false, // 重定向路由不在菜单中显示
        meta: {
            requireAuth: false
        }
    },
    {
        path: '/login',
        element: <Login />,
        showInMenu: false, // 登录页不在菜单中显示
        meta: {
            title: '用户登录',
            requireAuth: false, // 不需要认证
        }
    },
    {
        path: '/dashboard',
        element: <Dashboard />,
        showInMenu: true,
        meta: {
            title: 'menu.dashboard',
            icon: <DashboardOutlined />,
            order: 1,
            requireAuth: true, // 需要登录
            roles: [], // 所有角色都可访问
            permissions: [], // 无特殊权限要求
        }
    },
    {
        path: '/samples',
        element: <SampleManagement />,
        showInMenu: true,
        meta: {
            title: 'menu.sampleManagement',
            icon: <EnvironmentOutlined />,
            order: 2,
            requireAuth: true,
            roles: ['admin', 'manager', 'operator'], // 管理员、管理者、操作员可访问
            permissions: ['sample:read'], // 需要样品读取权限
        }
    },
    {
        path: '/devices',
        element: <DeviceManagement />,
        showInMenu: true,
        meta: {
            title: 'menu.deviceManagement',
            icon: <SettingOutlined />,
            order: 3,
            requireAuth: true,
            roles: ['admin', 'manager'], // 仅管理员和管理者可访问
            permissions: ['device:read'], // 需要设备读取权限
        }
    },
    {
        path: '/data',
        element: <DataQuery />,
        showInMenu: true,
        meta: {
            title: 'menu.dataQuery',
            icon: <DatabaseOutlined />,
            order: 4,
            requireAuth: true,
            roles: [], // 所有角色都可访问
            permissions: ['data:read'], // 需要数据读取权限
        }
    },
    {
        path: '/data-comparison',
        element: <DataComparison />,
        showInMenu: true,
        meta: {
            title: '对比分析',
            icon: <SwapOutlined />,
            order: 5,
            requireAuth: true,
            roles: [], // 所有角色都可访问
            permissions: ['data:read'], // 需要数据读取权限
        }
    },
    // 演示页面分组
    {
        path: '/theme-demo',
        element: <ThemeAnimationDemo />,
        showInMenu: true,
        meta: {
            title: '主题动画演示',
            icon: <BulbOutlined />,
            order: 6,
            group: 'demo', // 分组标识
            groupTitle: '演示功能', // 分组标题
            groupIcon: <BulbOutlined />, // 分组图标
            requireAuth: true,
            roles: ['admin'], // 仅管理员可访问演示功能
            permissions: ['demo:access'],
        }
    },
    {
        path: '/tab-demo',
        element: <TabDemo />,
        showInMenu: true,
        meta: {
            title: 'Tab演示',
            icon: <BulbOutlined />,
            order: 7,
            group: 'demo', // 属于同一个分组
            groupTitle: '演示功能',
            groupIcon: <BulbOutlined />,
            requireAuth: true,
            roles: ['admin'], // 仅管理员可访问演示功能
            permissions: ['demo:access'],
        }
    },
    // 权限不足页面
    {
        path: '/403',
        element: <Forbidden />,
        showInMenu: false,
        meta: {
            title: '权限不足',
            requireAuth: false,
        }
    },
];

/**
 * 生成路由组件数组（用于 React Router）
 */
export const getRoutes = () => {
    return routeConfig.map(route => ({
        path: route.path,
        element: route.element,
    }));
};

/**
 * 生成菜单项数组（用于 Ant Design Menu）
 * @param {Function} t - i18n 翻译函数
 * @param {boolean} showDemoFeatures - 是否显示演示功能
 */
export const getMenuItems = (t, showDemoFeatures = true) => {
    let visibleRoutes = routeConfig
        .filter(route => route.showInMenu)
        .sort((a, b) => (a.meta?.order || 99) - (b.meta?.order || 99));

    // 如果不显示演示功能，过滤掉演示功能路由
    if (!showDemoFeatures) {
        visibleRoutes = visibleRoutes.filter(route => route.meta?.group !== 'demo');
    }

    // 按组分类路由
    const grouped = {};
    const ungrouped = [];

    visibleRoutes.forEach(route => {
        if (route.meta?.group) {
            if (!grouped[route.meta.group]) {
                grouped[route.meta.group] = {
                    routes: [],
                    groupTitle: route.meta.groupTitle,
                    groupIcon: route.meta.groupIcon,
                };
            }
            grouped[route.meta.group].routes.push(route);
        } else {
            ungrouped.push(route);
        }
    });

    // 生成菜单项
    const menuItems = [];

    // 添加未分组的菜单项
    ungrouped.forEach(route => {
        menuItems.push({
            key: route.path,
            icon: route.meta?.icon,
            label: typeof route.meta?.title === 'string' && route.meta.title.startsWith('menu.')
                ? (typeof t === 'function' ? t(route.meta.title) : route.meta.title)
                : route.meta?.title,
        });
    });

    // 添加分组菜单项
    Object.entries(grouped).forEach(([groupKey, groupData]) => {
        menuItems.push({
            key: `group-${groupKey}`,
            icon: groupData.groupIcon,
            label: groupData.groupTitle,
            children: groupData.routes.map(route => ({
                key: route.path,
                icon: route.meta?.icon,
                label: typeof route.meta?.title === 'string' && route.meta.title.startsWith('menu.')
                    ? (typeof t === 'function' ? t(route.meta.title) : route.meta.title)
                    : route.meta?.title,
            })),
        });
    });

    return menuItems;
};

/**
 * 根据路径获取页面标题
 * @param {string} path - 路由路径
 * @param {Function} t - i18n 翻译函数
 */
export const getPageTitle = (path, t) => {
    const route = routeConfig.find(route => route.path === path);
    if (!route?.meta?.title) return '';

    return typeof route.meta.title === 'string' && route.meta.title.startsWith('menu.')
        ? (typeof t === 'function' ? t(route.meta.title) : route.meta.title)
        : route.meta.title;
};

/**
 * 获取路由的面包屑配置
 * @param {string} path - 路由路径
 * @param {Function} t - i18n 翻译函数
 */
export const getBreadcrumbs = (path, t) => {
    const route = routeConfig.find(route => route.path === path);
    if (!route) return [];

    return [
        {
            title: typeof t === 'function' ? t('common.home') : 'Home',
            path: '/dashboard'
        },
        {
            title: getPageTitle(path, t),
            path: path
        }
    ];
};

/**
 * 为混合布局生成顶部菜单项
 * @param {Function} t - i18n 翻译函数
 * @param {boolean} showDemoFeatures - 是否显示演示功能
 */
export const getTopMenuItems = (t, showDemoFeatures = true) => {
    const menuItems = getMenuItems(t, showDemoFeatures);

    // 为混合布局重新组织菜单结构
    const dashboardItem = menuItems.find(item => item.key === '/dashboard');
    const otherItems = menuItems.filter(item => item.key !== '/dashboard');

    const result = [];

    // 添加仪表板
    if (dashboardItem) {
        result.push(dashboardItem);
    }

    // 将其他项目组织到"数据管理"下（除了分组菜单）
    const managementItems = otherItems.filter(item => !item.key.startsWith('group-'));
    const groupItems = otherItems.filter(item => item.key.startsWith('group-'));

    if (managementItems.length > 0) {
        result.push({
            key: 'management',
            label: '数据管理',
            children: managementItems
        });
    }

    // 添加分组菜单项（如演示功能）
    result.push(...groupItems);

    return result;
};

/**
 * 为混合布局生成侧边菜单项
 * @param {string} currentPath - 当前路径
 * @param {Function} t - i18n 翻译函数
 * @param {boolean} showDemoFeatures - 是否显示演示功能
 */
export const getSideMenuItems = (currentPath, t, showDemoFeatures = true) => {
    const allMenuItems = getMenuItems(t, showDemoFeatures);

    // 防御性检查：确保 currentPath 是有效的字符串
    if (!currentPath || typeof currentPath !== 'string') {
        // 如果路径无效，返回所有未分组的菜单项
        return allMenuItems.filter(item => !item.key.startsWith('group-'));
    }

    // 找到当前路径所属的分组
    const currentRoute = routeConfig.find(route => route.path === currentPath);
    const currentGroup = currentRoute?.meta?.group;

    if (currentGroup) {
        // 如果当前路径属于某个分组，显示该分组的菜单项
        const groupMenuItem = allMenuItems.find(item => item.key === `group-${currentGroup}`);
        return groupMenuItem ? groupMenuItem.children : [];
    } else {
        // 显示所有未分组的菜单项（包括仪表板）
        return allMenuItems.filter(item => !item.key.startsWith('group-'));
    }
};
